package com.bootdo.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.bootdo.blog.service.WechatService;
import com.bootdo.system.dao.BcuserDao;
import com.bootdo.system.domain.BcuserDO;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;

import com.jfinal.weixin.sdk.utils.JsonUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import java.util.*;

@Service
public class WechatServiceImpl extends ApiController implements WechatService {


    private static Logger logger =Logger.getLogger(WechatService.class);


    @Autowired
    private BcuserDao bcuserDao;


    @Override
    public ApiResult getUserInfoAndSave(String accessToken, String openId) {

        ApiConfig apiConfig = getApiConfig();
        ApiResult userInfo = SnsApi.getUserInfo(accessToken, openId);
        logger.info(JsonUtils.toJson(userInfo));
        Map<String, Object> map = new HashMap<>();
        map.put("openApi",openId);
        List<BcuserDO> list = bcuserDao.list(map);
        if(userInfo.isSucceed()&& (ListUtils.isEmpty(list)||list.get(0) == null)){
            bcuserDao.save(gennrateBcuser(userInfo));
        }

        return userInfo;
    }

    private BcuserDO gennrateBcuser(ApiResult userInfo) {

        BcuserDO bcuserDO = new BcuserDO();
        bcuserDO.setCity(userInfo.getStr("city"));
        bcuserDO.setNickname(userInfo.getStr("nickname"));
        bcuserDO.setSex(userInfo.getInt("sex")+"");
        bcuserDO.setProvince(userInfo.getStr("province"));
        bcuserDO.setCountry(userInfo.getStr("country"));
        bcuserDO.setHeadimgurl(userInfo.getStr("headimgurl"));
        bcuserDO.setUnionid(userInfo.getStr("unionid"));
        bcuserDO.setCreated(new Date());
        bcuserDO.setUpdated(new Date());
        bcuserDO.setOpenApi(userInfo.getStr("openid"));

        String privilege = JSON.toJSONString(userInfo.getList("privilege"));
        bcuserDO.setPrivilege(privilege);

        return bcuserDO;
    }


    @Override
    public ApiConfig getApiConfig() {
        ApiConfig apiConfig =new ApiConfig();
        apiConfig.setAppId("wx24dffff92fcc6bad");
        apiConfig.setAppSecret("dd19890387d1beb557ff9322c22d6b1f");
        apiConfig.setToken("verify_token");
        apiConfig.setEncodingAesKey("ozMYIVWlRF6IQKtlnDiSWoJt0LM6OqahlQpbEqCo2kO");
        ApiConfigKit.setThreadLocalApiConfig(apiConfig);
        return ApiConfigKit.getApiConfig();
    }

}
